package org.example.blog_manage.Controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.blog_manage.model.BlogInfo;
import org.example.blog_manage.model.UserInfo;
import org.example.blog_manage.service.BlogInfoService;
import org.example.blog_manage.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RequestMapping("/Blog")
@RestController
public class BlogInfoController {

    @Autowired
    private BlogInfoService blogInfoService;

    @GetMapping
    @RequestMapping("/getList")
    public List<BlogInfo> selectAll(){

        return blogInfoService.selectAll();
    }

    @RequestMapping("/blogDetail")
    public BlogInfo selectById(Integer blogId, HttpServletRequest request){
        String token = request.getHeader("user_token_key");
        Integer userId = JwtUtils.getUserInfoID(token);
        Boolean b = blogInfoService.compareUId(userId, blogId);
        BlogInfo blogInfo = blogInfoService.selectById(blogId);
        if(b){
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }

    @RequestMapping("/add")
    public Boolean insertBlogInfo(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
        //参数校验
        if(!StringUtils.hasLength(blogInfo.getTitle()) || !StringUtils.hasLength(blogInfo.getContent())){
            return false;
        }
        String token = request.getHeader("user_token_key");
        Integer userId = JwtUtils.getUserInfoID(token);
        BlogInfo blogInfo1 = new BlogInfo();
        blogInfo1.setUserId(userId);
        blogInfo1.setTitle(blogInfo.getTitle());
        blogInfo1.setContent(blogInfo.getContent());
        boolean b =  blogInfoService.insertBlogInfo(blogInfo1);
        return b ;
    }

    @RequestMapping("/deleteBlog")
    public Boolean deleteBlog(Integer blogId){

        return blogInfoService.deleteBlog(blogId);
    }

    @RequestMapping("/getBlogInfoDetail")
    public BlogInfo getBlogInfoDetail(Integer blogId){
        return blogInfoService.getBlogInfoDetail(blogId);
    }

    @RequestMapping("/update")
    public Boolean update(BlogInfo blogInfo){
        return blogInfoService.update(blogInfo);
    }
}
